<html>
<head>
  <title>ATL03 h_ph</title>
  <link rel="stylesheet" type="text/css" href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.54.0/mapbox-gl.css">
  <link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/readable/bootstrap.min.css" rel="stylesheet">
  <meta property="og:site_name" content="ATL03 h_ph"/>
  <meta property="og:title" content="ATL03 h_ph"/>
  <meta property="og:description" content=""/>
  <style>
    body {
      background-color: #000000;
      margin: 0;
    }
    #map {
      height: 100vh;
      width: 100%;
      margin: 0 auto;
    }
    #content {
      position:absolute;
      left: 20;
      right: 20;
      /* min-height:50px; */
      bottom: 20;
    }
    .sidecontainer {
      padding:20px;
    }
    a.mapboxgl-ctrl-logo {
      margin-left: 10px;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  <div id='content'>
    <h2>ATL03 photon received height (h_ph)</h2>
      <p><a
      href='https://nsidc.org/sites/nsidc.org/files/technical-references/ATL03%20Product%20Data%20Dictionary.pdf'>ATL03
      Data Dictionary</a></p>
  </div>
</body>
<script src="https://unpkg.com/deck.gl@^7.0.4/dist.min.js"></script>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.54.0/mapbox-gl.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">

  const { MapboxLayer, PointCloudLayer } = deck;
  mapboxgl.accessToken = 'pk.eyJ1IjoibGFuZHBsYW5uZXIiLCJhIjoiY2syNm43Y3F2MHV4bzNicGV5d2kyaXJ1dyJ9.4XEHIzZ4Psvemp0lH9l1NA';

  const map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/outdoors-v11',
    center: [10.51346780, -3.0930829],
    zoom: 13.99,
    hash: true
  });
  let currentCollection = 'ATL08';
  let currentGranuleId = '20190617150548_12270308_002_01';
  let filePrefix = `${currentCollection}_${currentGranuleId}`;
  
  // set dot brightness adjustment
  const brightness = 1.8
  const initialLayerId = 'deckgl-PointCloudLayer';
  let currentLayers = [];

  map.on('style.load', () => {
    map.addControl(new mapboxgl.NavigationControl());
    addPointLayer(filePrefix);
  });
  
  function addPointLayer(filePrefix, opts = { layerId: initialLayerId }) {
    const geoJSONUrl = `./geojsons/${filePrefix}.geojson`;
    $.getJSON(geoJSONUrl, function(geoJSON) {
      //console.log(JSON.stringify(geoJSON, null, 2));
      let pointSize = 0;
      const pointData = geoJSON.features.map(f => {
        let z = 0;
        let zrandomness = Math.random() * 20 - Math.random() * 20;
        let color;
        if (f.properties.collection === 'ATL08') {
          z = f.properties['dem_meters'];
          // 100 is a good size for atl08 and 5 for atl03
          pointSize = 100;
          color = [255, 228, 20, 100];
        } else if (f.properties.collection === 'ATL03') {
          z = f.properties['photon_height_meters'];
          z = z + zrandomness;
          pointSize = 2;
          color = [255, 25, 143 + z, 100];
        }

        return  {
          position: [
            f.geometry.coordinates[0], 
            f.geometry.coordinates[1],
            z
          ],
          color,
          properties: f.properties
        }
      });
      //console.log(JSON.stringify(pointData, null, 2));
      //console.log(`adding layer ${filePrefix}`)

      map.addLayer(new MapboxLayer({
        id: opts.layerId,
        type: PointCloudLayer,
        data: pointData,
        getPosition: d => d.position,
        getColor: d => d.color,
        getNormal: d => [-1, 0, 0],
        sizeUnits: 'meters',
        pointSize,
        opacity: 1,
        pickable: true,
        onClick: (info, event) => {
          // toggle layers
          if (currentCollection === 'ATL08') {
            currentCollection = 'ATL03';
            currentLayers = [];
            const beginningSegmentId = info.object.properties.beginning_segment_id;
            const endingSegmentId = info.object.properties.ending_segment_id;
            const middleSegmentId = (endingSegmentId - beginningSegmentId) / 2 + beginningSegmentId;
            for (let idx = beginningSegmentId; idx <= endingSegmentId; idx++) {
              let currentLayerId = `${idx}-layer`;
              currentLayers.push(currentLayerId);
              filePrefix = `${idx}_ATL03_${currentGranuleId}`;
              addPointLayer(filePrefix, { layerId: currentLayerId });
              if (idx === middleSegmentId) {
                map.flyTo({
                  center: info.lngLat,
                  zoom: 17.8,
                  bearing: -50,
                  pitch: 15
                });
              }
            }
            map.removeLayer(initialLayerId);
          } else {
            currentCollection = 'ATL08';
            currentLayers.forEach(function (layerId) {
              map.removeLayer(layerId);
            });
            currentLayers = [];
            filePrefix = `ATL08_${currentGranuleId}`;
            addPointLayer(filePrefix);
            map.flyTo({
              center: info.lngLat,
              zoom: 13.99,
              bearing: 0,
              pitch: 0
            });
          }
          return true;
        }
      }));
    });
  }

</script>
</html>
